package com.lntea.netty.im.handler.client;

import com.lntea.netty.im.packet.*;
import com.lntea.netty.im.codec.PacketCodeC;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.Date;
import java.util.UUID;

public class ClientHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(new Date() + ": 客户端开始登陆");

        // 创建登陆对象
        LoginRequestPacket packet = new LoginRequestPacket();
        packet.setUserId(UUID.randomUUID().toString());
        packet.setUserName("admin");
        packet.setPassword("admin");

        ByteBuf buffer = PacketCodeC.INSTANCE.encode(ctx.alloc(), packet);
        ctx.channel().writeAndFlush(buffer);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buffer = (ByteBuf) msg;

        Packet packet = PacketCodeC.INSTANCE.decode(buffer);
        if (packet instanceof LoginResponsePacket) {
            LoginResponsePacket respPacket = (LoginResponsePacket) packet;

            if (respPacket.getSuccess()) {
                // 登录成功
                System.out.println(new Date() + ": 客户端登陆成功");
            } else {
                // 登录失败
                System.out.println(new Date() + ": 客户端登陆失败，原因：" + respPacket.getReason());
            }
        } else if (packet instanceof MessageResponsePacket) {
            MessageResponsePacket respPacket = (MessageResponsePacket) packet;
            System.out.println(new Date() + String.format(": 收到服务端消息：%s", respPacket.getMessage()));
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.channel().flush();
    }
}
